package com.yinxing.webapi.shiro;

import com.yinxing.framework.exception.PrincipalTypeException;
import com.yinxing.framework.shiro.exception.RequiresUserException;
import lombok.Data;
import lombok.ToString;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Data
@ToString
public class LoginUser {

    /**
     * 用户ID(PK)
     */
    private long userId;

    /**
     * sessionID
     */
    private String authToken;

    /**
     * JwtTolen
     */
    private String jwtToken = "";

    /**
     * 用户名称
     */
    private String username;

    /**
     * 登录用户名
     */
    private String loginName;

    /**
     * 部门名称
     */
    private String deptName;

    /**
     * 用户角色
     */
    private Set<String> roles = new HashSet<>();

    /**
    * 用户权限
    */
    private Set<String> permissions = new HashSet<>();

    /**
     * 登录时间
     */
    private Date loginTime = new Date();

    /**
     * 用户IP
     */
    private String userHost;

    /**
     * 用户头像地址
     */
    private String profile;

    /**
     * 是否拥有角色
     * @param role 角色
     */
    public boolean hasRole(String role) {
        return roles.contains(role);
    }

    /**
     * 是否拥有权限
     * @param permission
     */
    public boolean hasPermission(String permission) {
        return permission.contains(permission);
    }

    /**
     * 获取当前登录账户
     */
    public static LoginUser current() {
        Subject subject = SecurityUtils.getSubject();

        if(!subject.isAuthenticated()) {
            throw new RequiresUserException("获取当前账户数据失败");
        }

        Object principal = subject.getPrincipal();
        if(!(principal instanceof LoginUser)) {
            throw new PrincipalTypeException("登录账户类型不是{LoginUser}");
        }

        return (LoginUser) principal;
    }
}
